package cn.chendd.compress.sevenz;

import net.sf.sevenzipjbinding.ICryptoGetTextPassword;
import net.sf.sevenzipjbinding.IOutCreateCallback;
import net.sf.sevenzipjbinding.ISequentialInStream;
import net.sf.sevenzipjbinding.SevenZipException;
import net.sf.sevenzipjbinding.impl.OutItem;
import net.sf.sevenzipjbinding.impl.OutItemFactory;
import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
import java.util.List;

/**
 * @author chendd
 * @date 2023/03/05 19:45
 */
public class SevenZCompressCallBack implements IOutCreateCallback<OutItem> , ICryptoGetTextPassword {

    private File rootFile;
    private List<Item> items;
    private String password;

    public SevenZCompressCallBack(File rootFile , List<Item> items , String password) {
        this.rootFile = rootFile;
        this.items = items;
        this.password = password;
    }

    @Override
    public String cryptoGetTextPassword() throws SevenZipException {
        return password;
    }

    @Override
    public void setOperationResult(boolean operationResultOk) throws SevenZipException {

    }

    @Override
    public OutItem getItemInformation(int index, OutItemFactory<OutItem> outItemFactory) throws SevenZipException {
        OutItem outItem = outItemFactory.createOutItem();
        Item item = this.items.get(index);
        File file = item.getFile();
        String path = StringUtils.substringAfter(file.getAbsolutePath(), rootFile.getAbsolutePath() + File.separator);
        //压缩包根目录的文件
        if (StringUtils.isEmpty(path)) {
            outItem.setPropertyPath(file.getName());
        } else {
            outItem.setPropertyPath(path);
        }
        if (file.isDirectory()) {
            outItem.setPropertyIsDir(true);
        }
        outItem.setDataSize(file.length());
        return outItem;
    }

    @Override
    public ISequentialInStream getStream(int index) throws SevenZipException {

        File file = this.items.get(index).getFile();
        if (file.isFile()) {
            try {
                return new RandomAccessFileInStream(new RandomAccessFile(file , "r"));
            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            }
        }
        return null;
    }

    @Override
    public void setTotal(long total) throws SevenZipException {

    }

    @Override
    public void setCompleted(long complete) throws SevenZipException {

    }
}
